package com.example.hackotontest.communication;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import com.example.hackotontest.R;
import com.example.hackotontest.R.id;
import com.example.hackotontest.R.layout;
import com.example.hackotontest.communication.ScrumMasterCommunicationActivity.ServerThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SalahorCommunicationActivity extends Activity {

	private EditText clientsMessage;
	private Button sendMessage;
	private String scrumMasterIpAddress = "10.0.2.2";
	private boolean connected = false;
	Socket socket = null;

	// server
	private Handler handler = new Handler();
	private TextView messageReceivedFromServer;
	private static final String SALAHOR_SERVER_IP = "10.0.2.15";
	private ServerSocket serverSocket;
	private static final int LISTENING_PORT = 8082;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.salahor_communication);

		clientsMessage = (EditText) findViewById(R.id.client_message);
		sendMessage = (Button) findViewById(R.id.send_message);
		sendMessage.setOnClickListener(sendListener);

		// server
		messageReceivedFromServer = (TextView) findViewById(R.id.server_received_message);

		Thread fst = new Thread(new ServerThread());
		fst.start();
	}

	// server side
	public class ServerThread implements Runnable {

		public void run() {
			try {
				if (SALAHOR_SERVER_IP != null) {
					handler.post(new Runnable() {
						@Override
						public void run() {
							messageReceivedFromServer.setText("Listening on IP: " + SALAHOR_SERVER_IP);
						}
					});
					serverSocket = new ServerSocket(LISTENING_PORT);
					while (true) {
						// listen for incoming clients
						Socket client = serverSocket.accept();
						handler.post(new Runnable() {
							@Override
							public void run() {
								messageReceivedFromServer.setText("Connected.");
							}
						});

						try {
							BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
							String line = null;
							while ((line = in.readLine()) != null) {
								final String reportLine = line;
								Log.d("ServerActivity", line);
								handler.post(new Runnable() {
									@Override
									public void run() {
										messageReceivedFromServer.setText(reportLine);
										// do whatever you want to the front end
										// this is where you can be creative
									}
								});
							}
							break;
						} catch (Exception e) {
							handler.post(new Runnable() {
								@Override
								public void run() {
									messageReceivedFromServer.setText("Oops. Connection interrupted. Please reconnect your phones.");
								}
							});
							e.printStackTrace();
						}
					}
				} else {
					handler.post(new Runnable() {
						@Override
						public void run() {
							messageReceivedFromServer.setText("Couldn't detect internet connection.");
						}
					});
				}
			} catch (Exception e) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						messageReceivedFromServer.setText("Error");
					}
				});
				e.printStackTrace();
			}
		}
	}

	// CLIENT

	private OnClickListener sendListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// if (!connected) {
			// serverIpAddress = serverIp.getText().toString();
			// if (!serverIpAddress.equals("")) {
			Thread cThread = new Thread(new ClientThread());
			cThread.start();
			// }
			// }
		}
	};

	public class ClientThread implements Runnable {

		public void run() {
			try {

				if (!connected) {
					InetAddress serverAddr = InetAddress.getByName(scrumMasterIpAddress);
					Log.d("ClientActivity", "C: Connecting...");
					socket = new Socket(serverAddr, 8081);
					connected = true;
				}
				// while (connected) {
				try {
					Log.d("ClientActivity", "C: Sending command.");
					PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
					// where you issue the commands
					out.println(clientsMessage.getText().toString());
					Log.d("ClientActivity", "C: Sent.");
				} catch (Exception e) {
					Log.e("ClientActivity", "S: Error", e);
				}
				// }
				// socket.close();
				// Log.d("ClientActivity", "C: Closed.");
			} catch (Exception e) {
				Log.e("ClientActivity", "C: Error", e);
				connected = false;
			}
		}
	}
}
